/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: SprringContextHold
 * Author:   zhouheng
 * Date:     2018/6/18 11:16
 * Description: ioc容器工具
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.hengby.hengcrud.core.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 〈一句话功能简述〉<br> 
 * 〈ioc容器工具〉
 *
 * @author zhouheng
 * @create 2018/6/18
 * @since 1.0.0
 */
@Component
@Slf4j
public class SpringContextHold implements ApplicationContextAware{

    public static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHold.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplication(){
        return applicationContext;
    }

    public static <T> T getBean(String beanName){
        return (T)applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();
        log.info(applicationContext.getBean(requiredType).toString());
        return applicationContext.getBean(requiredType);
    }

    private static void assertApplicationContext() {
        if (SpringContextHold.applicationContext == null) {
            throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
        }
    }
}